﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data;
using DAL;
using System.Text;
using System.IO;
using Library;

namespace PeisongWeb.admin
{
    public partial class priceContrast : adminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("CI", 1))
                {
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }
            }
        }

        public DataSet GetDataFromExcel()
        {
            //上传Excel文件

            string savePath = Server.MapPath(Resource.UploadPath + "original/");
            savePath += File1.FileName;
            File1.SaveAs(savePath);
            //string filename = UpdateXls(this.File1);//上传XLS文件

            //EXCEL 的连接串
            string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                "Data Source=" + savePath + ";" +
                "Extended Properties=Excel 12.0;";
            //EXCEL 的连接串只对office2003有效的
            //string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
            //"Data Source=" + savePath + ";" +
            //"Extended Properties=Excel 8.0;";
            //建立EXCEL的连接
            OleDbConnection objConn = new OleDbConnection(sConnectionString);
            DataSet objDataset1 = new DataSet();
            objConn.Open();
            try
            {
                OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1＄]", objConn);
                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
                objAdapter1.SelectCommand = objCmdSelect;
                objAdapter1.Fill(objDataset1, "XLData");
            }
            catch (Exception)
            {
                //throw ex;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "alert('导入出错！')", true);
            }
            finally
            {
                objConn.Close();//关闭EXCEL的连接
                Library.FileLib.delUploadFile(File1.FileName);  //删除Excel
            }
            return objDataset1;
        }

        protected void btnContrast_Click(object sender, EventArgs e)
        {
            if (Request.Headers["Accept"] != "*/*")
            {
                string strContentType = File1.PostedFile.ContentType;
                if (strContentType == "application/vnd.ms-excel" || strContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                {
                    int rowCount = 0;
                    int succount = 0;
                    int errorcount = 0;
                    string strErrorNo = "";
                    DataSet dsrepeater = new DataSet();
                    DataSet ds = GetDataFromExcel();
                    DataTable dt = new DataTable("contrast");
                    DataColumn dtc = new DataColumn("productNo", typeof(string));
                    dt.Columns.Add(dtc);
                    dtc = new DataColumn("productName", typeof(string));
                    dt.Columns.Add(dtc);
                    dtc = new DataColumn("businessNatureName", typeof(string));
                    dt.Columns.Add(dtc);
                    dtc = new DataColumn("contrastPrice", typeof(double));
                    dt.Columns.Add(dtc);
                    dtc = new DataColumn("sellerPrice", typeof(double));
                    dt.Columns.Add(dtc);
                    dtc = new DataColumn("priceDifference", typeof(double));
                    dt.Columns.Add(dtc);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds.Tables[0].Rows)
                        {
                            rowCount++;
                            PriceProductEntity priceproductentity = Contrast(row);
                            if (priceproductentity != null)
                            {
                                if (priceproductentity.ProductName != null)
                                {
                                    succount++;
                                    DataRow dr = dt.NewRow();
                                    dr["productNo"] = priceproductentity.ProductId;
                                    dr["productName"] = priceproductentity.ProductName;
                                    dr["businessNatureName"] = priceproductentity.BusinessNatureName;
                                    dr["priceDifference"] = priceproductentity.PriceDifference;
                                    dr["contrastPrice"] = priceproductentity.ContrastPrice;
                                    dr["sellerPrice"] = priceproductentity.SellerPrice;
                                    dt.Rows.Add(dr);
                                }
                                else
                                {
                                    errorcount++;
                                    strErrorNo += priceproductentity.ProductId.ToString() + "、";
                                }
                            }
                            else
                            {
                                Library.Script.ClientMsg("对不起，您操作有误，请正确操作(第" + rowCount + "行数据格式错误)！");
                                return;
                            }
                        }
                        dsrepeater.Tables.Add(dt);
                        if (errorcount != 0)
                        {
                            StringBuilder strmsg = new StringBuilder("<ul>");
                            strmsg.AppendFormat("<li>{0}个产品数据没有找到！</li>", errorcount.ToString());
                            strmsg.AppendFormat("<li>&nbsp;&nbsp;(编号为{0}数据不正确！)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li><br/>", strErrorNo);
                            strmsg.Append("</ul>");
                            ScriptManager1.AddScript("Ext.MessageBox.confirm('请确认', '请选择是否继续导入！<br/><br/>" + strmsg.ToString() + "', function(btn){if(btn=='no'){window.location.href='index.aspx';}});");
                        }

                        if (succount != 0)
                        {
                            AspNetPager1.RecordCount = succount;
                            rpt_list.DataSource = dsrepeater.Tables[0];
                            rpt_list.DataBind();
                        }
                    }

                }
                else
                {
                    Library.Script.ClientMsg("请选择正确的 Excel 文件！");
                    return;
                }

            }
        }

        public PriceProductEntity Contrast(DataRow dr)
        {
            try
            {
                PriceProductEntity priceProductentity = new PriceProductEntity();
                priceProductentity.ProductId = dr[0].ToString();
                priceProductentity.BusinessNature = dr[1].ToString();
                priceProductentity.Price = Convert.ToDouble(dr[2].ToString());
                PriceProductEntity priceProductReturn = logic.priceProduct.pricecontrast(priceProductentity);
                return priceProductReturn;
            }
            catch (Exception)
            {
                return null;
            }
        }

       

        protected void lbtnDownload_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=template.xls");
            string filename = Server.MapPath("../app_resource/EmailTemplate/template.xls");
            Response.TransmitFile(filename);
        }
        //public string BusinessNature(string businessnature)
        //{
        //    if (businessnature == "1")
        //        return "工厂食堂级";
        //    else if (businessnature == "2")
        //        return "机关事业单位级";
        //    else if (businessnature == "3")
        //        return "院校级";
        //    else
        //        return "酒店餐饮级";

        //}

    }
}
